<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import { OptionItems } from "@/api";
// 根据传入的获取方法自动获得options的组件

interface Props {
  fetchfunc?: (p?: any) => OptionItems[] | Promise<OptionItems[]>;
  modelValue?: string | number | Array<string | number>;
  options?: OptionItems[];
  params?: any
}
interface Emits {
  (t: "update:modelValue", v: string | number | Array<string | number>): void;
  // 只有从fetchfunc获取的结果才会触发该事件
  (t: "fetchResult", v: OptionItems[]): void;
}
const props = defineProps<Props>();
// 最终options结果
const options = ref<OptionItems[]>([]);
const emit = defineEmits<Emits>();

async function getOptions() {
  if (Array.isArray(props.options) && props.options.length) {
    options.value = props.options;
  } else if (props.fetchfunc) {
    const result = await props.fetchfunc(props.params);
    options.value = result;
    emit("fetchResult", result);
  }
}
onMounted(() => {
  getOptions();
});
watch(() => props.options, () => getOptions());
watch(() => props.params, () => getOptions(), { deep: true })
defineExpose({
  refresh: () => {
    emit("update:modelValue", "");
    getOptions();
  },
});
</script>
<template>
  <ElSelect :model-value="modelValue" @update:model-value="emit('update:modelValue', $event)">
    <ElOption v-for="item of options" :key="item.value" :label="item.label" :value="item.value"
      :disabled="item.disabled" />
  </ElSelect>
</template>
